<template>
  <div class="app-container">
    <header class="header">
      <el-form :model="queryParams" ref="queryForm" inline>
        <el-form-item label="支付平台" prop="payTypeId">
          <el-select v-model="queryParams.payTypeId" clearable @change="changeQeuryParams">
            <el-option v-for="item in payList" :value="item.typeId" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="代理名称" v-if="isAdmin" prop="agentId">
          <el-select
            v-model="queryParams.agentId"
            @change="
              getClientList();
              changeQeuryParams();
            "
            filterable
            clearable
            style="width: 240px"
          >
            <el-option v-for="item in agentList" :label="item.userName" :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商户名称" prop="clientId" v-if="!isClient">
          <el-select v-model="queryParams.clientId" filterable clearable style="width: 240px" @change="changeQeuryParams">
            <el-option v-for="item in clientList" :label="item.userName" :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="date" label="日期">
          <el-date-picker v-model="monthQuery" @change="changeMounth" type="date" placeholder="选择月份" value-format="YYYY-MM-DD" :clearable="false">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="flex mb-[20px]">
        <el-button type="primary" icon="Search" @click="browseMonth">浏览整月</el-button>
        <el-button type="primary" icon="Refresh" @click="refreshList">刷新列表</el-button>
        <el-button icon="Refresh" @click="cleanSelected">清空选中</el-button>
      </div>
    </header>
    <div class="top">
      <NumTable
        ref="NumTable"
        :prevDays="prevDays"
        :days="days"
        :nextDays="nextDays"
        v-model:checkList="queryParams.dateList"
        @chrenBack="changeNumber"
        :timeId="monthQuery"
      />
    </div>
    <div class="middel">
      <topCard ref="topCard" :queryParams="queryParams" :monthQuery="monthQuery" />
    </div>
    <div class="bottom">
      <el-tabs v-model="activeName">
        <el-tab-pane label="未结算" lazy name="first">
          <unsettledTable
            ref="unsettledTable"
            @changeSuccess="unsettledChangeSuccess"
            :activeName="activeName"
            :monthQuery="monthQuery"
            :queryParams="queryParams"
          />
        </el-tab-pane>
        <el-tab-pane label="已结算" lazy name="second">
          <settledTableVue
            ref="settledTableVue"
            @changeSuccess="settledChangeSuccess"
            :monthQuery="monthQuery"
            :activeName="activeName"
            :queryParams="queryParams"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import NumTable from './components/numAndDate.vue';
import settledTableVue from './components/settledTable.vue';
import unsettledTable from './components/unsettledTable.vue';
import topCard from './components/topCard.vue';
import { getClient as selectUserList } from '@/api/pay/PayApp';
import { getUnSettNum } from '@/api/pay/PaySettlement';
import { selecTypetList } from '@/api/pay/PayType/index';
import useUserStore from '@/store/modules/user';
export default {
  components: { settledTableVue, unsettledTable, topCard, NumTable },
  data() {
    return {
      date: new Date(),
      queryParams: {
        payTypeId: '',
        appId: '',
        clientId: '',
        agentId: '',
        dateList: []
      },
      days: [],
      prevDays: [],
      nextDays: [],
      activeName: '',
      userList: [],
      clientList: [],
      monthQuery: '',
      payList: [],
      agentList: []
    };
  },
  dicts: ['pay_type', 'stripe_status'],
  async mounted() {
    this.initSelect();
    this.activeName = 'first';
    await this.getPayList();
    this.initMounth();
  },
  computed: {
    monthParams() {
      let opt = {
        payType: '',
        agentId: '',
        userId: '',
        year: this.monthQuery?.split('-')[0] || '',
        month: this.monthQuery?.split('-')[1] || ''
      };
      Object.assign(opt, this.queryParams);
      return opt;
    },
    isAdmin() {
      const { isAdmin } = useUserStore();
      return isAdmin;
    },
    isClient() {
      const { isClient } = useUserStore();
      return isClient;
    }
  },
  methods: {
    async getAgentList() {
      selectUserList({
        roleKey: 'agent'
      }).then((response) => {
        this.agentList = response.data;
      });
    },
    async getClientList() {
      let opt = {
        roleKey: 'client'
      };
      this.queryParams.agentId ? (opt.agentId = this.queryParams.agentId) : '';
      selectUserList(opt).then((response) => {
        this.clientList = response.data;
      });
    },
    async getPayList() {
      let res = await selecTypetList();
      this.payList = res.data;
      this.queryParams.payTypeId = res.data[0].typeId;
    },
    // 浏览整月
    browseMonth() {
      this.$refs.NumTable.isBrowseMonth = true;
      this.$nextTick(() => {
        this.queryParams.dateList = [];
      });
      this.changeQeuryParams();
    },
    cleanSelected() {
      this.queryParams.dateList = [];
    },
    // 刷新列表
    async refreshList() {
      if (this.activeName == 'first') {
        this.$refs.unsettledTable?.getTableData();
        this.$refs.topCard.getUnSettToTalData();
        await this.setDayData(this.monthQuery?.split('-')[0], this.monthQuery?.split('-')[1]);
      } else {
        this.$refs.settledTableVue?.getTableData();
        this.$refs.topCard.getUnSettToTalData();
        await this.setDayData(this.monthQuery?.split('-')[0], this.monthQuery?.split('-')[1]);
      }
    },
    // 补零
    fillZero(val) {
      let str = val.toString();
      return str.length < 2 ? (str = '0' + str) : str;
    },
    // 未结算列表提交成功
    unsettledChangeSuccess() {
      this.$refs.settledTableVue?.getTableData();
      this.$refs.topCard.getUnSettToTalData();
      this.setDayData(this.monthQuery?.split('-')[0], this.monthQuery?.split('-')[1]);
    },
    // 已结算列表提交成功
    settledChangeSuccess() {
      this.$refs.unsettledTable?.getTableData();
      this.$refs.topCard.getUnSettToTalData();
      this.setDayData(this.monthQuery?.split('-')[0], this.monthQuery?.split('-')[1]);
    },
    // 更改月份
    changeMounth(val) {
      this.queryParams.dateList = [];
      // 判断当前月份中是否有选中月份
      if (val.includes(this.prevDays[0].date) || val.includes(this.days[0].date) || val.includes(this.nextDays[0].date)) {
        // 当前列表有选中的日期
      } else {
        // 没有则请求后台
        this.setDayData(val?.split('-')[0], val?.split('-')[1]);
      }
      // 将值选中
      this.$nextTick(() => {
        this.$refs.NumTable.checkAction(val);
      });
      this.changeQeuryParams();
    },
    changeNumber(val) {
      this.queryParams.dateList = val;
      this.$refs.unsettledTable?.getTableData();
      this.$refs.settledTableVue?.getTableData();
      this.$refs.topCard.getUnSettToTalData();
    },
    // 当参数发生变化
    async changeQeuryParams() {
      this.$refs.unsettledTable?.getTableData();
      this.$refs.settledTableVue?.getTableData();
      this.$refs.topCard.getUnSettToTalData();
      await this.setDayData(this.monthQuery?.split('-')[0], this.monthQuery?.split('-')[1]);
    },
    // 初始化下拉框数据
    async initSelect() {
      selectUserList().then((response) => {
        this.userList = response.data;
      });
      this.getAgentList();
      this.getClientList();
    },
    // 选择日期
    daysChange() {},
    // 获取月份天数
    getDaysOfMonth(year, month) {
      var date = new Date(year, month, 0);
      var days = date.getDate();
      let opt = {};
      for (var i = 1; i < days + 1; i++) {
        opt[i] = 0;
      }
      return opt;
    },
    // 更换月份
    mothChange(val) {
      let year = new Date(val).getFullYear();
      let month = new Date(val).getMonth() + 1;
      this.getDaysOfMonth(year, month);
      this.queryParams.days = [];
    },
    // 默认当前月份
    async initMounth() {
      let year = new Date().getFullYear();
      let month = new Date().getMonth() + 1;
      let day = new Date().getDate();
      this.monthQuery = `${year}-${month >= 10 ? month : '0' + month}-${day}`;
      await this.setDayData(year, month);
    },
    // 获取月份对应数量
    async getSetNum(opt, month, year) {
      let newOpt = JSON.parse(JSON.stringify(opt));
      this.monthParams.month = month;
      this.monthParams.year = year;
      // 更换参数
      let res = await getUnSettNum(this.monthParams);
      Object.assign(newOpt, res.data);
      let arr = [];
      for (const key in newOpt) {
        let str = {
          day: this.fillZero(key),
          num: newOpt[key].unsettled || 0,
          month: this.fillZero(month),
          settledNum: newOpt[key].settled || 0,
          year,
          date: year + '-' + this.fillZero(month),
          dateDay: year + '-' + this.fillZero(month) + '-' + this.fillZero(key)
        };
        arr.push(str);
      }
      return arr;
    },
    // 赋值给每月天数
    async setDayData(yearStr, monthStr) {
      await this.setDayDataFake(yearStr, monthStr);
      let month = Number(parseInt(monthStr));
      let year = Number(parseInt(yearStr));
      if (month == 1) {
        this.prevDays = await this.getSetNum(this.getDaysOfMonth(year - 1, 12), 12, year - 1);
      } else {
        this.prevDays = await this.getSetNum(this.getDaysOfMonth(year, month - 1), month - 1, year);
      }
      this.days = await this.getSetNum(this.getDaysOfMonth(year, month), month, year);
      if (month < 12) {
        this.nextDays = await this.getSetNum(this.getDaysOfMonth(year, month + 1), month + 1, year);
      } else {
        this.nextDays = await this.getSetNum(this.getDaysOfMonth(year + 1, 1), 1, year + 1);
      }
    },
    // 赋值默认值没有数量
    async setDayDataFake(yearStr, monthStr) {
      let month = Number(parseInt(monthStr));
      let year = Number(parseInt(yearStr));
      if (month == 1) {
        let num = this.getDaysOfMonth(year - 1, 12);
        let arr = [];
        for (let key in num) {
          arr.push({
            year: year - 1,
            month: 12,
            day: this.fillZero(key),
            num: 0,
            settledNum: 0
          });
        }
        this.prevDays = arr;
      } else {
        let num = this.getDaysOfMonth(year, month - 1);
        let arr = [];
        for (let key in num) {
          arr.push({
            year: year,
            month: this.fillZero(month - 1),
            day: this.fillZero(key),
            num: 0,
            settledNum: 0
          });
        }
        this.prevDays = arr;
      }
      let num = this.getDaysOfMonth(year, month);
      let arr = [];
      for (let key in num) {
        arr.push({
          year: year,
          month: this.fillZero(month),
          day: this.fillZero(key),
          num: 0,
          settledNum: 0
        });
      }
      this.days = arr;
      if (month < 12) {
        let num = this.getDaysOfMonth(year, month + 1);
        let arr = [];
        for (let key in num) {
          arr.push({
            year: year,
            month: this.fillZero(month + 1),
            day: this.fillZero(key),
            num: 0,
            settledNum: 0
          });
        }
        this.nextDays = arr;
      } else {
        let num = this.getDaysOfMonth(year + 1, 12);
        let arr = [];
        for (let key in num) {
          arr.push({
            year: year + 1,
            month: this.fillZero('1'),
            day: this.fillZero(key),
            num: 0,
            settledNum: 0
          });
        }
        this.nextDays = arr;
      }
      return true;
    }
  }
};
</script>

<style lang="scss" scoped>
.have_num {
  background-color: #e1e1e1;
}
.con .label {
  font-size: 13px;
}
:deep(.el-pagination) {
  margin-top: 20px;
  text-align: center;
}
.top :deep(.is-checked) {
  background-color: #1890ff;
  box-shadow: 0px 0px 1px 2px rgba(24, 144, 255, 0.4);
}
.top :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #fff;
}
.top :deep(.el-checkbox) {
  width: 40px;
  height: 40px;
  padding: 2px;
  color: #666;
  border-radius: 10px;
  box-sizing: border-box;
}
.top :deep(.el-checkbox__inner) {
  display: none;
}
.top :deep(.el-checkbox__label) {
  font-size: 18px;
  padding: 0;
}
.list {
  .con {
    height: 200px;
    text-align: center;
    display: flex;
    .num_title {
      height: 100%;
      display: flex;
      justify-content: space-between;
      flex-flow: column;
      padding-top: 50px;
      padding-bottom: 16px;
      margin-right: 20px;
    }
    .list_container {
      display: flex;
      flex: 1;
      overflow-y: auto;
      > div {
        border-top: 1px solid #666;
        border-right: 1px solid #666;
        border-bottom: 1px solid #666;
        &:nth-child(1) {
          border-left: 1px solid #666;
        }
      }
      .header {
        height: 50px;
        line-height: 50px;
        border-bottom: 1px solid #666;
        font-size: 20px;
        font-weight: bold;
        color: #6e6a6a;
      }
      .wrap {
        color: #666;
        height: calc(100% - 50px);
        display: flex;
        justify-content: space-between;
        column-gap: 30px;
        flex-shrink: 1;
        padding-right: 6px;
        > div {
          height: 100%;
          display: flex;
          justify-content: space-between;
          flex-flow: column;
          position: relative;
          padding-bottom: 10px;
          &::after {
            // content: "";
            height: 100%;
            width: 1px;
            position: absolute;
            right: -50%;
            top: 0;
            background-color: #666;
          }
          &::before {
            // content: "";
            height: 1px;
            width: calc(100% + 30px);
            position: absolute;
            left: 0;
            top: 50%;
            background-color: #666;
          }
          &:nth-last-child(1)::after {
            display: none;
          }
          &:nth-last-child(1)::before {
            // content: "";
            height: 1px;
            width: calc(100% + 6px);
            position: absolute;
            left: 0;
            top: 50%;
            background-color: #666;
          }
        }
      }
    }
    .top {
      padding: 2px;
      width: 40px;
      height: 40px;
      text-align: center;
      line-height: 40px;
      box-sizing: border-box;
    }
  }
}
.num_list {
  display: flex;
  overflow: auto;
}
</style>
